/**
 * Copyright (C) 2018-2021
 * All rights reserved, Designed By www.yixiang.co

 */
package co.yixiang.modules.mp.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.enums.AppFromEnum;
import co.yixiang.modules.mp.domain.YxWechatReply;
import co.yixiang.modules.mp.service.YxWechatReplyService;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.dto.WechatUserDto;
import co.yixiang.utils.IpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


@Slf4j
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private YxWechatReplyService yxWechatReplyService;

    @Autowired
    private YxUserService userService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxService,
                                    WxSessionManager sessionManager) throws WxErrorException {


        String str = "你好，欢迎关注yshop!";
        YxWechatReply wechatReply = yxWechatReplyService.isExist("subscribe");
        if (!ObjectUtil.isNull(wechatReply)) {
            str = JSONObject.parseObject(wechatReply.getData()).getString("content");
        }

        log.info("关注事件 wxMessage：{}   context：{}", wxMessage, JSONObject.toJSONString(context));

        String openId = wxMessage.getFromUser();
        this.logger.info("关注用户 OPENID: " + openId);
        //String unionId = wxMessage.getUnionId();
        WxMpUser wxMpUser = wxService.getUserService().userInfo(openId);


        //如果开启了UnionId
        if (StrUtil.isNotBlank(wxMpUser.getUnionId())) {
            openId = wxMpUser.getUnionId();
        }

        YxUser yxUser = userService.getOne(Wrappers.<YxUser>lambdaQuery()
                .eq(YxUser::getUsername, wxMpUser.getUnionId()), false);


        if (ObjectUtil.isNull(yxUser)) {

            //过滤掉表情
            String nickname = wxMpUser.getNickname();
            log.info("昵称：{}", nickname);
            //用户保存
            String ip = IpUtil.getLocalIP();
            YxUser user = YxUser.builder()
                    .username(openId)
                    .nickname(nickname)
                    .avatar(wxMpUser.getHeadImgUrl())
                    .addIp(ip)
                    .lastIp(ip)
                    .userType(AppFromEnum.WECHAT.getValue())
                    .build();

            //构建微信用户
            WechatUserDto wechatUserDTO = WechatUserDto.builder()
                    .nickname(nickname)
                    .openid(wxMpUser.getOpenId())
                    .unionId(wxMpUser.getUnionId())
                    .sex(wxMpUser.getSex())
                    .language(wxMpUser.getLanguage())
                    .city(wxMpUser.getCity())
                    .province(wxMpUser.getProvince())
                    .country(wxMpUser.getCountry())
                    .headimgurl(wxMpUser.getHeadImgUrl())
                    .subscribe(wxMpUser.getSubscribe())
                    .subscribeTime(wxMpUser.getSubscribeTime())
                    .build();

            user.setWxProfile(wechatUserDTO);
            userService.save(user);
        } else {
            WechatUserDto wechatUser = yxUser.getWxProfile();
            if ((StrUtil.isBlank(wechatUser.getOpenid()) && StrUtil.isNotBlank(wxMpUser.getOpenId()))
                    || (StrUtil.isBlank(wechatUser.getUnionId()) && StrUtil.isNotBlank(wxMpUser.getUnionId()))) {
                wechatUser.setOpenid(wxMpUser.getOpenId());
                wechatUser.setUnionId(wxMpUser.getUnionId());

                yxUser.setWxProfile(wechatUser);
            }

            //yxUser.setUserType(AppFromEnum.WECHAT.getValue());
            userService.updateById(yxUser);
        }

        try {
            WxMpXmlOutMessage msg = WxMpXmlOutMessage.TEXT()
                    .content(str)
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser())
                    .build();
            return msg;
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }


        return null;
    }


}
